const fs = require('fs');
const { URL } = require('url');
const QRCode = require('qrcode');

const distPath = './dist/'
let options = process.argv.slice(2);
let env = options.length > 0 ? options[0] : '';
console.log("gulp env", options, env);

// 志愿卡激活,口令激活二维码生成
function getVipEncode() {
	let domain = options.length > 0 ? options[1] : ''; //不含https
	let qrcodeUrl = "https://www.lzy-gaokao.com/qrcode.php?size=6&value=";
	let str1 =`https://${domain}/?uri=/pages/topic/activation/activate-code`;//口令激活
	let str2 =`https://${domain}/card`;//志愿卡激活
	let outPath = distPath+'qr/';
	const opts = {
		errorCorrectionLevel: 'M',
		type: 'image/png',
		quality: 1,
		margin: 2,
		width: 300,
		height: 300
	};
	const getQrcode = (str, name="qrcode") => (
		QRCode.toDataURL(str, opts)
		  .then(url => {
				url = url.split('base64,')[1]
				let buffer = Buffer.from(url, 'base64');
				// 写入文件到系统
				fs.writeFile(outPath+name+'.png', buffer, { encoding: 'base64' }, function(err) {
				if (err) {
				console.log(err);
				} else {
					console.log(name+'文件保存成功', str);
					return false;
				}
			});
		  })
		  .catch(err => {
			console.error(err);
		  })
	)
	
	if(domain) {
		getQrcode(str1,'口令激活');
		getQrcode(str2,'志愿卡激活');
	} else {
		console.warn('env必须配置域名，不含https')
		return false;
	}
}

// 文件处理
function getFile(){
	let path = new URL("file:///D:/phpstudy_pro/WWW/csh-tools/web/mp/test/delete.js");
	
	// console.log(path)
	fs.readFile(path, 'utf8', (err,data) => {
	console.log('err', err);
	  if (err) throw err;
	  console.log('data', data);
	  
	  const updatedContent = data.replace(/name/g, 'nameChange');
	  
	  	fs.writeFile(path, updatedContent, function (err) {
	  	  if (err) throw err;
	  	  console.log('It\'s saved!');
	  	  fs.appendFile(path, 'data to append2', function (err) {
	  	    if (err) throw err;
	  	    console.log('The "data to append2" was appended to file!');
	  	  });
	  	});
	});

}

if(env === 'file') {
	getFile()
}
else if(env === 'qrcode') {
	getVipEncode()
}

